import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入登录注册组件
import regPage from '@/views/Reg/regPage.vue'
import loginPage from '@/views/Login/loginPage.vue'
import mainPage from '@/views/Main/mainPage.vue'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'

import store from '@/store/index.js'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 声明路由规则
const routes = [
  { path: '/reg', component: regPage },
  { path: '/login', component: loginPage },
  {
    path: '/',
    component: mainPage,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/user-info', component: UserInfo },
      { path: '/user-avatar', component: UserAvatar },
      { path: '/user-pwd', component: UserPwd },
      { path: '/art-cate', component: ArtCate },
      { path: '/art-list', component: ArtList }

    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path !== '/login' && to.path !== '/reg' && !store.state.user.token) {
    Vue.prototype.$message.error('您还没登录')
    return next('/login')
  }
  next()
})

export default router
